package com.demo.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import com.jplus.framework.mvc.annotation.Controller;
import com.jplus.framework.mvc.annotation.Request;
import com.jplus.framework.mvc.bean.Result;
import com.jplus.framework.mvc.bean.View;
import com.jplus.framework.util.FormatUtil;
import com.jplus.plugins.rpc.Constant;
import com.jplus.plugins.rpc.core.ZkFactory;

@Controller
@Request.All("/rpc")
public class RpcAction {
	static {
		ZkFactory.createConnection(Constant.ZK_ADDRESS, Constant.ZK_SESSION_TIMEOUT);
	}

	@Request.Get("/nodelist")
	public View nodelist() {
		return new View();
	}

	@Request.Get("/provider")
	public View provider() {
		return new View();
	}

	@Request.Get("/ajaxZkTree/{type}")
	public Result ajaxZkTree(int type) {
		try {
			List<Map<String, Object>> tree = new ArrayList<Map<String, Object>>();
			if (type == 0)
				tree = forEach("/", ZkFactory.getZK(), -1);
			if (type == 1)
				tree = forEach(Constant.ZK_REGISTRY_PATH, ZkFactory.getZK(), -1);
			return new Result().OK().DATA(tree);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().FAIL().DATA(e.getMessage());
		}
	}

	private static List<Map<String, Object>> forEach(String path, ZooKeeper zk, int dep) throws KeeperException, InterruptedException {
		List<Map<String, Object>> alllist = new ArrayList<Map<String, Object>>();
		List<String> list = zk.getChildren(path, false);
		++dep;
		if (list.size() > 0) {
			for (String str : list) {
				String temp = FormatUtil.formatPath(path + "/" + str);
				byte[] data = zk.getData(temp, false, null);
				Map<String, Object> node = new HashMap<String, Object>();
				node.put("key", temp.substring(temp.lastIndexOf("/")));
				node.put("data", new String(data == null ? new byte[] {} : data));
				List<Map<String, Object>> clist = forEach(temp, zk, dep);
				if (clist.size() > 0)
					node.put("childs", clist);
				alllist.add(node);
			}
		}
		return alllist;
	}

	public static void main(String[] args) throws KeeperException, InterruptedException {
		List<Map<String, Object>> list = forEach(Constant.ZK_REGISTRY_PATH, ZkFactory.getZK(), -1);
		System.out.println(FormatUtil.toJSONString(list));
	}
}
